/**
 * Processes transactions from a Merged Transaction File, producing an output DVD file 
 * and an updated Master DVD File.
 * Usage: master-dvd-file merged-transaction-file output-dvd-file new-master-dvd-file
 */
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * The main driver class for the back-end, do not instantiate this class.
 * 
 * @author Adam Contois, Adam Domurad, Pat Goebel
 * 
 */
public class DVDBackend {

	/**
	 * The main program, usage: [master-dvd-file] [merged-transaction-file] [output-dvd-file] [new-master-dvd-file]
	 * 
	 * @param args
	 *            The command-line arguments are passed: [master-dvd-filename,
	 *            merged-transaction-filename, output-dvd-file,
	 *            new-master-dvd-file]
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {

		if (args.length < 4) {
			System.out.println("Expected usage master-dvd-filename, "
							+ "merged-transaction-filename, output-dvd-file, new-master-dvd-file");
			return;
		}

		String masterdvdfile = args[0];
		String mastertransfile = args[1];
		String outputdvdfile = args[2];
		String outputmasterdvdfile = args[3];

		try {

			DVDTransaction[] transactions = createFromMergedTransactionFile(mastertransfile);
			DVDInventory inventory = DVDInventory
					.createFromMasterDVDFile(masterdvdfile);

			performTransactions(inventory, transactions);

			inventory.toDVDFile(outputdvdfile);
			inventory.toMasterDVDFile(outputmasterdvdfile);
		} catch (InvalidFileFormat iff) {
			System.out.println("ERROR: " + iff.getMessage());
		}
	}

	/**
	 * Creates transactions from a Merged Transaction File.
	 * 
	 * @param filename
	 *            file name of the merged transaction file
	 * @return an array of DVDTransaction objects
	 */
	static public DVDTransaction[] createFromMergedTransactionFile(
			String filename) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader(filename));
		List<DVDTransaction> entries = new ArrayList<DVDTransaction>();
		String s;
		while ((s = br.readLine()) != null) {
			System.out.println(s.length());
			DVDTransaction newEntry = DVDTransaction
					.createTransactionFromLine(s);
			if (newEntry == null)
				return null;
			entries.add(newEntry);

		}
		DVDTransaction[] return_array = new DVDTransaction[entries.size()];
		return entries.toArray(return_array);
	}

	/**
	 * Perform the transactions that have been read into the array
	 * 'transactions' on the 'inventory'.
	 * 
	 * @param inventory
	 *            the inventory of the DVD system
	 * @param transactions
	 *            the transactions to process
	 */
	static public void performTransactions(DVDInventory inventory,
			DVDTransaction[] transactions) {
		for (DVDTransaction trans : transactions) {
			inventory.performTransaction(trans);
		}
	}

}
